/* eslint-disable react-hooks/exhaustive-deps */
/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 *
 * Generated with the TypeScript template
 * https://github.com/react-native-community/react-native-template-typescript
 *
 * @format
 */

import { useThrottleFn, useWhyDidYouUpdate } from 'ahooks';
import React, { useEffect, useRef, useState } from 'react';
import {
  Image,
  SafeAreaView,
  ScrollView,
  StyleSheet,
  Text,
  TouchableOpacity,
  View,
  NativeModules,
  DeviceEventEmitter
} from 'react-native';
import { RNCamera } from 'react-native-camera';
import * as Brightness from 'expo-brightness';
import { Dimensions } from 'react-native';
import { uploadRequest } from '../../utils/UploadUtils';
import ResultDisplay from '../ResultDisplay';
import Button from '../Button';
import { useSelector } from '../../store/hook';

const screenWidth = Math.round(Dimensions.get('window').width);
const screenHeight = Math.round(Dimensions.get('window').height);

const HomeScreen: React.FC = () => {
  //相片地址
  const [image, setImage] = useState<string>();
  // 是否隐藏相机
  const [hideCamera, setHideCamera] = useState<boolean>(true);
  //系统亮度
  const systemBrightness = React.useRef(0);
  const permissionsGranted = React.useRef(false);
  // 控制是否显示结果
  const [isDisplayResult, setIsDisplayResult] = useState(false);
  //识别结果
  const [result, setResult] = useState<any>([]);
  //相机引用
  const cameraRef = useRef<RNCamera>(null);
  //提供计算亮度差
  const beforeLightness = useRef<number>(0);
  //防止多次timeout
  const interval = useRef<NodeJS.Timeout | null>(null)
  const lightThreshold = useSelector(state => state.settingConfig.lightThreshold);

  const displayTips = (res: any) => {
    console.log('result', res);
    setIsDisplayResult(true);
    if (res) {
      setResult(res);
    } else {
      setResult(undefined);
    }
    setTimeout(() => {
      setIsDisplayResult(false);
    }, 5 * 1000)
  };

  //请求控制亮度权限
  const requireBrightnessPermissions = async () => {
    try {
      let permissions = await Brightness.getPermissionsAsync();
      console.log('permissions', permissions);
      if (permissions.status !== 'granted' && permissions.canAskAgain) {
        permissions = await Brightness.requestPermissionsAsync();
        console.log('permissions-second', permissions);
      }
      if (permissions.status === 'granted') {
        permissionsGranted.current = true;
        systemBrightness.current = await Brightness.getBrightnessAsync();
        Brightness.setSystemBrightnessAsync(1);
      }
    } catch (error) {
      console.log('error', error);
    }
    return () => {
      if (permissionsGranted.current) {
        Brightness.setSystemBrightnessAsync(systemBrightness.current);
      }
    };
  };
  //光线传感器
  const configureLightSensor = () => {
    NativeModules.SensorManager.startLightSensor(100);
    DeviceEventEmitter.addListener('LightSensor', async (data) => {
      const sub = data.light - beforeLightness.current;
      beforeLightness.current = (data.light);
      if (sub > parseInt(lightThreshold)) {
        brighten();
        if (!interval.current) {
          interval.current = setTimeout(() => {
            closeCamera();
            interval.current = null
          }, 20000)
        }
      }
    });
  };

  useEffect(() => {
    configureLightSensor();
  }, []);

  useEffect(() => {
    requireBrightnessPermissions();
  }, []);

  useEffect(() => {
    setTimeout(() => {
      Brightness.setBrightnessAsync(0);
    }, 5000);
  }, []);

  const cameraConfig = useSelector(state => state.cameraConfig);

  useWhyDidYouUpdate('camera', { cameraConfig });

  //todo 轮训拍照
  // useInterval(() => {
  //   takePicture();
  // }, interval);

  //拍照 function
  const takePicture = async () => {
    if (cameraRef) {
      const picResult = await cameraRef.current?.takePictureAsync();
      if (picResult) {
        const { uri } = picResult;
        console.log(uri);
        setImage(uri);
        const apiResult = await uploadRequest(uri);
        displayTips(apiResult);
      }
    }
  };

  // 拍照增加防抖
  const { run: takePictureThrottle } = useThrottleFn(
    () => {
      takePicture();
    },
    { wait: 1000 },
  );

  //点亮相机和屏幕
  const brighten = async () => {
    setHideCamera(false);
    Brightness.setBrightnessAsync(1);
  };

  const closeCamera = async () => {
    setHideCamera(true);
    Brightness.setBrightnessAsync(0);
  };

  return (
    <ScrollView style={styles.screen}>
      {isDisplayResult && <ResultDisplay result={result} />}
      {hideCamera === false ? (
        <View>
          <RNCamera style={styles.rnCamera} type="back" ref={cameraRef} />
          <View style={styles.control}>
            <Button onPress={brighten}>OpenCamera</Button>
            <Button onPress={closeCamera}>ShutDownCamera</Button>
            <Button onPress={() => takePictureThrottle()}>
              Take A picture
            </Button>
          </View>

          <View style={styles.imageView}>
            <Image
              source={{
                height: 600,
                width: 350,
                uri: image,
              }}
            />
          </View>
        </View>
      ) : (
        <View>
          <TouchableOpacity
            style={styles.fullScreenTouchable}
            activeOpacity={1}
            onPress={brighten}>
            <Text>Please click the screen to continue</Text>
          </TouchableOpacity>
        </View>
      )}
    </ScrollView>
  );
};

const styles = StyleSheet.create({
  screen: {
    // flex: 1,
    backgroundColor: '#F2F2FC',
    // justifyContent: 'space-between',
  },
  saveArea: {
    backgroundColor: '#464775',
  },
  topBar: {
    height: 50,
    backgroundColor: '#464775',
    alignItems: 'center',
    justifyContent: 'center',
  },
  caption: {
    height: 120,
    width: '100%',
    alignItems: 'center',
    justifyContent: 'center',
    marginBottom: 30,
  },
  control: {
    height: 180,
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
  },
  rnCamera: {
    alignSelf: 'center',
    flex: 1,
    margin: 40,
    width: 0.8 * Dimensions.get('window').width,
    height: 0.5 * Dimensions.get('window').height
  },
  btn: {
    flex: 1,
    height: 50,
    borderRadius: 4,
    backgroundColor: '#62d1bc',
    paddingHorizontal: 24,
    paddingVertical: 12,
    marginVertical: 8,
    marginLeft: 10,
  },
  btnText: {
    fontSize: 14,
    color: '#ffffff',
    textAlign: 'center',
    lineHeight: 14,
  },
  imageView: {
    // width: '100%',
    // height: 200,
    color: '#ffffff',
    alignItems: 'center',
  },
  input: {
    height: 40,
    margin: 12,
    borderWidth: 1,
    padding: 10,
  },
  fullScreenTouchable: {
    alignItems: 'center',
    justifyContent: 'center',
    width: screenWidth,
    height: screenHeight,
    fontSize: 50,
  },
});

export default HomeScreen;
